package com.apache.member.service.impl;

import java.util.Date;
import java.util.List;

import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.database.model.Page;
import com.apache.exception.BusinessException;
import com.apache.member.common.ConstantData;
import com.apache.member.common.DateUtil;
import com.apache.member.entity.Member;
import com.apache.member.entity.MemberRole;
import com.apache.member.manager.MemberManager;
import com.apache.member.manager.MemberRoleManager;
import com.apache.tools.MD5Utils;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.entity.User;
import com.apache.uct.manager.UserManager;

public class MemberManagerImpl implements MemberManager {

	protected IDao memberDao;
	protected final String entityName = "com.apache.member.entity.Member";
	protected final String memberRoleEntity = "com.apache.member.entity.MemberRole";
	private UserManager userManager;
	private MemberRoleManager memberRoleManager;

	public void setMemberDao(IDao memberDao) {
		this.memberDao = memberDao;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	@Override
	public List<Member> chechUserExist(ParamsVo<User> vo2) {
		MethodParam param = new MethodParam("UserByUserEname", "", "", entityName);
		param.setParams("userEname", String.valueOf(vo2.getParams("userEname")));
		List<Member> list = memberDao.select(param);
		if (list != null && list.size() > 0) {
			return list;
		}
		return null;
	}

	/**
	 * add by  yaojs 2015-06-16
	 * description:  
	 * @param vo
	 * @return
	 * @throws BusinessException  
	 * @author Administrator 
	 * @update 2015-6-16
	 */
	public String saveMemberRoleInfo(ParamsVo<Member> vo) throws BusinessException {
		Member member = vo.getObj();
		String infoId = Validator.generate();
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		String cacheKey = "";
		//String cacheKey="member_"+infoId;
		member.setMemberId(infoId);
		MethodParam param = new MethodParam("Member", cacheKey, "", entityName);
		param.setVaule(member);
		if (memberDao.insert(param)) {
			return saveMemberRoles(member, cacheKey);
		}
		return "";
	}

	public boolean editInfo(ParamsVo<Member> vo) throws BusinessException {
		Member member = vo.getObj();
		if (Validator.isNotNull(member.getMemberId())) {
			String cacheKey = "";
			//String cacheKey="member_"+member.getMemberId();
			MethodParam param = new MethodParam("Member", cacheKey, "", entityName);
			param.setVaule(member);
			return memberDao.edit(param);
		}
		return false;
	}

	/**
	 * 更新member的基础信息和角色信息 ，事务控制不安全(因为在此之前会调用controller的deleteMemberRole方法)
	 * description:  
	 * @param vo
	 * @return
	 * @throws BusinessException  
	 * @author Administrator 
	 * @update 2015-6-17
	 */
	public boolean editMemberInfoAndRole(ParamsVo<Member> vo) throws BusinessException {
		Member member = vo.getObj();
		if (Validator.isNotNull(member.getMemberId())) {
			String cacheKey = "";
			//String cacheKey="member_"+member.getMemberId();
			MethodParam param = new MethodParam("Member", cacheKey, "", entityName);
			param.setVaule(member);
			if (memberDao.edit(param)) {
				String flag = saveMemberRoles(member, cacheKey);
				if (!"".equals(flag)) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 更新member的基础信息和角色信息，事务控制安全 
	 * description:  
	 * @param vo
	 * @return
	 * @throws BusinessException  
	 * @author Administrator 
	 * @update 2015-6-17
	 */
	public String editMemberAndSaveMemberRole(ParamsVo<Member> vo) throws BusinessException {
		Member member = vo.getObj();
		LoginUser loginUser = (LoginUser) vo.getParams("loginUser");
		String memberRoleId = null;
		if (Validator.isNotNull(member.getMemberId())) {
			String cacheKey = "";
			member.setUpdateTime(DateUtil.getNowTime());
			member.setUpdateUserEname(loginUser.getUserEname());
			if (this.editInfo(vo)) {

				String roleId = (String) vo.getParams("roleId");
				ParamsVo<MemberRole> memberRoleVo = new ParamsVo<MemberRole>();
				MemberRole memberRole = new MemberRole();
				if (Validator.isNotNull(roleId)) {
					memberRole.setRoleId(roleId);
					memberRole.setAuditStatus(ConstantData.AuditStatus.AUDITING);
					memberRoleVo.setObj(memberRole);
					if (memberRoleManager.editInfo(memberRoleVo)) {
						memberRoleId = roleId;
					}

				} else {
					memberRole.setMemberId(member.getMemberId());
					memberRole.setAuditStatus(ConstantData.AuditStatus.AUDITING);
					memberRole.setMemberEname(member.getMemberEname());
					memberRole.setMemberCname(member.getMemberCname());
					memberRole.setRoleEname(member.getMemberRoles());
					memberRoleVo.setObj(memberRole);
					memberRoleId = memberRoleManager.saveInfo(memberRoleVo);
				}

				vo.setParams("pid", memberRoleId);

			}
		}
		return memberRoleId;
	}

	/**
	 * 重构方法：根据member中memberRoles是否为空，执行该操作
	 * description:  
	 * @param member
	 * @param cacheKey  
	 * @author yaojs 
	 * @update 2015-6-19
	 */
	public boolean deleteMemberRoles(Member member, String cacheKey) {
		MethodParam param2 = new MethodParam("ByProperty", cacheKey, "", memberRoleEntity);
		param2.setParams("memberId", member.getMemberId());
		@SuppressWarnings("unchecked")
		List<MemberRole> oddRoleList = memberDao.select(param2);
		if (!Validator.isEmpty(oddRoleList)) {
			for (MemberRole mr : oddRoleList) {
				MethodParam param4 = new MethodParam("ById", cacheKey, "", memberRoleEntity);
				param4.setInfoId(mr.getRoleId());
				MemberRole info = (MemberRole) memberDao.selectById(param4);
				if (Validator.isEmpty(info)) {
					continue;
				}
				param4.setVaule(info);
				// 当前行必须加上否则报错
				param4.setParams("roleId", mr.getRoleId());
				param4.setDelete(true);
				if (!memberDao.delete(param4)) {
					return false;
				}
			}
		}
		return true;
	}

	public boolean deleteInfo(ParamsVo<Member> vo) throws BusinessException {
		String infoId = vo.getInfoId();
		if (Validator.isNull(infoId)) {
			return false;
		}
		String cacheKey = "";
		//String cacheKey="member_"+infoId;
		String mark = Validator.getDefaultStr(String.valueOf(vo.getParams("isDelete")), "true");
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		param.setInfoId(infoId);
		Member info = (Member) memberDao.selectById(param);
		if (Validator.isEmpty(info)) {
			return false;
		}
		param.setVaule(info);//此处需要先将状态值赋值为删除状态
		if ("false".equals(mark)) {//逻辑删除
			param.setKey("Member");
			return memberDao.edit(param);
		} else {
			param.setParams("memberId", infoId);
			param.setDelete(true);
			return memberDao.delete(param);
		}
	}

	public Page getPageInfo(ParamsVo<Member> vo) {
		String orderBy = (String) vo.getParams("orderBy");
		MethodParam param = setMethodParams(vo, 2);
		if (Validator.isEmpty(orderBy)) {
			param.setOrderby("update_time desc,member_level desc,audit_status desc,create_time desc");
		}
		int pageSize = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "10"));
		int pageIndex = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "1"));
		param.setPageIndex(pageIndex);
		param.setPageSize(pageSize);
		if (!Validator.isEmpty(vo.getParams("userRoles"))) {
			param.setParams("userRoles", (String) vo.getParams("userRoles"));
		}

		if (!Validator.isEmpty(vo.getParams("userDeptIds"))) {
			param.setParams("userDeptIds", (String) vo.getParams("userDeptIds"));
		}

		if (Validator.isNotNull((String) vo.getParams("clientManager"))) {
			param.setParams("clientManager", (String) vo.getParams("clientManager"));
		}
		Page page = memberDao.pageSelect(param);
		return page;
	}

	public List<Member> getList(ParamsVo<Member> vo) {
		MethodParam param = setMethodParams(vo, 2);
		param.setOrderby("updateTime,createTime");
		return memberDao.select(param);
	}

	public long countInfo(ParamsVo<Member> vo) {
		MethodParam param = setMethodParams(vo, 1);
		return memberDao.count(param);
	}

	private MethodParam setMethodParams(ParamsVo<Member> vo, int type) {
		String methodKey = Validator.getDefaultStr(vo.getMethodKey(), "ByProperty");
		StringBuffer sb = new StringBuffer(memberDao.getSql(type));
		MethodParam param = new MethodParam(methodKey, "", "", entityName);
		Member member = vo.getObj();
		if (Validator.isNotNull(member.getMemberEname())) {
			sb.append(" and memberEname = :memberEname");
			param.setParams("memberEname", member.getMemberEname());
		}
		if (Validator.isNotNull(member.getMemberCname())) {
			sb.append(" and memberCname like :memberCname");
			param.setParams("memberCname", member.getMemberCname());
		}
		if (Validator.isNotNull(member.getShortName())) {
			sb.append(" and shortName = :shortName");
			param.setParams("shortName", member.getShortName());
		}
		if (Validator.isNotNull(member.getMemberType())) {
			sb.append(" and memberType = :memberType");
			param.setParams("memberType", member.getMemberType());
		}
		if (Validator.isNotNull(member.getOrgType())) {
			sb.append(" and orgType = :orgType");
			param.setParams("orgType", member.getOrgType());
		}
		if (Validator.isNotNull(member.getMobile())) {
			sb.append(" and mobile = :mobile");
			param.setParams("mobile", member.getMobile());
		}
		if (Validator.isNotNull(member.getPhone())) {
			sb.append(" and phone = :phone");
			param.setParams("phone", member.getPhone());
		}
		if (Validator.isNotNull(member.getEmail())) {
			sb.append(" and email = :email");
			param.setParams("email", member.getEmail());
		}
		if (Validator.isNotNull(member.getRegTime())) {
			sb.append(" and regTime = :regTime");
			param.setParams("regTime", member.getRegTime());
		}
		if (Validator.isNotNull(member.getClientManager())) {
			sb.append(" and clientManager = :clientManager");
			param.setParams("clientManager", member.getClientManager());
		}
		if (Validator.isNotNull(member.getCertType())) {
			sb.append(" and certType = :certType");
			param.setParams("certType", member.getCertType());
		}
		if (Validator.isNotNull(member.getCertNo())) {
			sb.append(" and certNo = :certNo");
			param.setParams("certNo", member.getCertNo());
		}
		if (Validator.isNotNull(member.getValidityPeriod())) {
			sb.append(" and validityPeriod = :validityPeriod");
			param.setParams("validityPeriod", member.getValidityPeriod());
		}
		if (Validator.isNotNull(member.getMemberLevel())) {
			sb.append(" and memberLevel = :memberLevel");
			param.setParams("memberLevel", member.getMemberLevel());
		}
		if (Validator.isNotNull(member.getInfoFrom())) {
			sb.append(" and infoFrom = :infoFrom");
			param.setParams("infoFrom", member.getInfoFrom());
		}
		if (Validator.isNotNull(member.getCreateUserEname())) {
			sb.append(" and createUserEname = :createUserEname");
			param.setParams("createUserEname", member.getCreateUserEname());
		}
		if (Validator.isNotNull(member.getCreateTime())) {
			sb.append(" and createTime = :createTime");
			param.setParams("createTime", member.getCreateTime());
		}
		if (Validator.isNotNull(member.getUpdateUserEname())) {
			sb.append(" and updateUserEname = :updateUserEname");
			param.setParams("updateUserEname", member.getUpdateUserEname());
		}
		if (Validator.isNotNull(member.getUpdateTime())) {
			sb.append(" and updateTime = :updateTime");
			param.setParams("updateTime", member.getUpdateTime());
		}
		if (Validator.isNotNull(member.getStatus())) {
			sb.append(" and status = :status");
			param.setParams("status", member.getStatus());
		}
		if (Validator.isNotNull(member.getAuditStatus())) {
			sb.append(" and auditStatus = :auditStatus");
			param.setParams("auditStatus", member.getAuditStatus());
		}
		if (Validator.isNotNull(member.getDeptId())) {
			sb.append(" and deptId = :deptId");
			param.setParams("deptId", member.getDeptId());
		}
		if (Validator.isNotNull(member.getMemberNo())) {
			sb.append(" and memberNo = :memberNo");
			param.setParams("memberNo", member.getMemberNo());
		}

		param.setSqlStr(sb.toString());
		return param;
	}

	public String saveInfo(ParamsVo<Member> vo) throws BusinessException {
		Member member = vo.getObj();
		String infoId = "";
		if (Validator.isEmpty(member)) {
			infoId = Validator.generate();
		} else {
			infoId = member.getMemberId();
		}
		member.setMemberId(infoId);
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		String cacheKey = "";
		MethodParam param = new MethodParam("Member", cacheKey, "", entityName);
		param.setVaule(member);
		if (memberDao.insert(param)) {
			return infoId;
		}
		return "";
	}

	public String saveMemberAndUser(ParamsVo<Member> vo) throws BusinessException {
		Member member = vo.getObj();
		String infoId = Validator.generate();
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		String cacheKey = "";// "member_" + infoId;
		member.setMemberId(infoId);
		MethodParam param = new MethodParam("Member", cacheKey, "", entityName);
		param.setVaule(member);
		if (Validator.isNotNull(this.saveMemberAndRoles(vo))) {
			User user = new User();
			user.setUserEname(member.getMemberEname());
			user.setUserCname(member.getMemberCname());
			user.setUserType(member.getMemberType());
			user.setUserStatus(1);
			user.setMobile(member.getMobile());
			user.setEmail(member.getEmail());
			String userPass = MD5Utils.MD5(Validator.getDefaultStr((String) vo.getParams("userPass"), "123456"));
			user.setUserPass(userPass);
			user.setCreateTime(new Date().getTime());
			user.setDeptId(member.getDeptId());
			//给会员用户设置机构id,以后分配该机构权限
			//			String memberOrgId = ConfigUtil.getInstance().getValueByKey("config.properties", "memberOrgId");
			//			user.setOrgId(memberOrgId);
			ParamsVo paramsVo = new ParamsVo();
			paramsVo.setInfoId(infoId);
			paramsVo.setObj(user);
			String saveInfo = userManager.saveInfo(paramsVo);
			return infoId;
		}
		return "";
	}

	@Override
	public boolean deleteMemberAndUser(ParamsVo<Member> vo) {
		if (deleteInfo(vo)) {
			ParamsVo<User> userVo = new ParamsVo<User>();
			userVo.setInfoId(vo.getInfoId());
			return userManager.deleteInfo(userVo);
		}
		return false;
	}

	//TODO 2016-4-7以后新加的方法在下面
	public Page getExpertList(ParamsVo<Member> vo) {
		MethodParam param = new MethodParam("ByMemberRole", "", "", entityName);
		param.setParams("roleEname", String.valueOf(vo.getParams("roleEname")));
		param.setParams("shortName", String.valueOf(vo.getParams("shortName")));
		param.setParams("auditStatus", ConstantData.AuditStatus.AUDIT_PASS);
		param.setParams("status", ConstantData.UserStatus.START);
		param.setParams("orderBy", " order by t1.create_time desc ");
		int pageSize = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "10"));
		int pageIndex = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "1"));
		param.setPageIndex(pageIndex);
		param.setPageSize(pageSize);
		Page page = memberDao.pageSelect(param);
		return page;
	}

	/**
	 * 添加会员并且添加会员角色
	 * insert member;insert memberRoles;
	 */

	public String saveMemberAndRoles(ParamsVo<Member> vo) throws BusinessException {
		Member member = vo.getObj();
		String infoId = "";
		infoId = Validator.generate();
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		String cacheKey = "";
		//String cacheKey="member_"+infoId;
		member.setMemberId(infoId);
		MethodParam param = new MethodParam("Member", cacheKey, "", entityName);
		param.setVaule(member);
		if (memberDao.insert(param)) {
			String roleId = saveMemberRoles(member, cacheKey);
			vo.setParams("roleId", roleId);
			if (Validator.isNotNull(roleId)) {
				ParamsVo<User> userVo = new ParamsVo<User>();
				User user = new User();
				user.setUserId((String) vo.getParams("userId"));
				user.setBjcaUserid(infoId);
				if (Validator.isNotNull(member.getMobile())) {
					user.setMobile(member.getMobile());
				}
				user.setUserType(member.getMemberType());
				user.setUserCname(member.getMemberCname());
				userVo.setObj(user);
				userManager.editInfo(userVo);
			}
			return infoId;
		}
		return "";
	}

	/**
	 * 重构方法实现保存会员角色信息
	 * description:  保存会员的角色信息
	 * @param member : 会员对象
	 * @param cacheKey : 缓存key 
	 * @author yaojs 
	 * @update 2015-6-19
	 */
	public String saveMemberRoles(Member member, String cacheKey) {
		if (null != member.getMemberRoles() && !"".equals(member.getMemberRoles())) {
			String memberRoles = member.getMemberRoles();
			String[] roles = memberRoles.split(",");
			for (String s1 : roles) {
				MemberRole memberRole = new MemberRole();
				memberRole.setMemberId(member.getMemberId());
				memberRole.setMemberCname(member.getMemberCname());
				memberRole.setMemberEname(member.getMemberEname());
				memberRole.setRoleEname(s1);
				memberRole.setAuditStatus(ConstantData.AuditStatus.AUDITING);
				ParamsVo<MemberRole> vo = new ParamsVo<MemberRole>();
				vo.setObj(memberRole);
				return memberRoleManager.saveInfo(vo);
			}
		}
		return member.getMemberId();
	}

	public void setMemberRoleManager(MemberRoleManager memberRoleManager) {
		this.memberRoleManager = memberRoleManager;
	}

	//////////////////////////////////////////////////2016-7-8整理//////////////////////////////////////////////////////////////

	public Object execute(ParamsVo<Member> vo) {

		if ("checkMemberEname".equals(vo.getKey())) {
			return this.countInfo(vo);//long
		}

		return null;
	}

	public Object getInfoById(ParamsVo<Member> vo) {
		String infoId = vo.getInfoId();
		String cacheKey = "";
		//String cacheKey="member_"+infoId;
		if (Validator.isNull(infoId)) {
			return null;
		}

		String methodKey = "ById";
		if (Validator.isNotNull(vo.getMethodKey())) {
			methodKey = vo.getMethodKey();
		}

		MethodParam param = new MethodParam(methodKey, cacheKey, "", entityName);
		param.setInfoId(infoId);
		return memberDao.selectById(param);
	}
}
